package com.atguigu.daijia.driver.service.impl;

import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.driver.client.CosFeignClient;
import com.atguigu.daijia.driver.config.MinioProperties;
import com.atguigu.daijia.driver.service.FileService;
import com.atguigu.daijia.model.vo.driver.CosUploadVo;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {

    private final CosFeignClient cosFeignClient;
    private final MinioProperties minioProperties;

    /**
     * 上传文件
     * @param file
     * @param path
     * @return
     */
    @Override
    public CosUploadVo uploadFile(MultipartFile file, String path) {
        return cosFeignClient.upload(file, path).getData();
    }

    /**
     * 上传文件到 MinIO
     * @param file
     * @return
     */
    @Override
    public String uploadToMinIO(MultipartFile file) {
        try {
            // 创建一个 MinIO 的客户端对象
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioProperties.getEndpointUrl())
                    .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                    .build();

            // 查看是否有名为 daijia 的 bucket
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());

            // 如果不存在，那么此时就创建一个新的桶
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {
                // 如果存在打印信息
                System.out.println("Bucket " + minioProperties.getBucketName() + " already exists.");
            }

            // 获取上传文件后缀名
            String extFileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

            // 设置文件名称。使用当前年月日作为上传文件目录；使用 UUID 作为文件名，避免重复上传同名文件导致文件覆盖
            String fileName = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + UUID.randomUUID().toString().replaceAll("-", "") + extFileName;

            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .object(fileName)
                    .build();

            minioClient.putObject(putObjectArgs);

            // 构建 MinIO 上传文件地址并返回
            return minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + fileName;
        } catch (Exception e) {
            throw new GuiguException(ResultCodeEnum.UPLOAD_FILE_TO_MINIO_FAIL);
        }
    }
}
